#include <mutex>
#include <thread>

std::mutex m1, m2;

void threadA() {
    std::unique_lock<std::mutex> lock1(m1, std::defer_lock);
    std::unique_lock<std::mutex> lock2(m2, std::defer_lock);
    std::lock(lock1, lock2);  // 正确顺序：m1 → m2
    // 操作共享数据
}

void threadB() {
    std::unique_lock<std::mutex> lock1(m2, std::defer_lock);
    std::unique_lock<std::mutex> lock2(m1, std::defer_lock);
    std::lock(lock1, lock2);  // 错误顺序：m2 → m1
    // 操作共享数据
}

int main() {
    std::thread t1(threadA);
    std::thread t2(threadB);
    t1.join();
    t2.join();
    return 0;
}
